package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.config.RedissonConfig;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hh
 * @since 2023-1-15
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    //阻塞队列
//    private final BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);//指定了队列的大小
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();//创建只能有一个线程的线程池

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());//submit为提交任务给线程池
    }

    private  class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    VoucherOrder voucherOrder = (VoucherOrder) rabbitTemplate.receiveAndConvert("boot-queue", -1);//负数为阻塞运行，队列中没有消息时就阻塞
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }
    private IVoucherOrderService proxy;

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本，判断是否能购买
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int i = result.intValue();
        if (i != 0) {
            return Result.fail(i == 1 ? "库存不足" : "你已经抢购过该优惠券了");
        }
        //返回值为0，表示可以下单，将订单对象保存到阻塞队列
        VoucherOrder voucherOrder=new VoucherOrder();
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        long orderId = redisIdWorker.nextId("order");//工具类生成订单id
        voucherOrder.setId(orderId);
        sendMessage(voucherOrder);//发送到消息队列
        //将对象添加到阻塞队列
//        orderTasks.add(voucherOrder);
        proxy  =(IVoucherOrderService) AopContext.currentProxy();//获取代理对象，事务依赖于代理对象
        return Result.ok(voucherOrder);
    }
        //查询优惠券
//        SeckillVoucher voucher = iSeckillVoucherService.getById(voucherId);
//        LocalDateTime beginTime = voucher.getBeginTime();
//        LocalDateTime endTime = voucher.getEndTime();
//        Integer stock = voucher.getStock();//获取库存数量
//        LocalDateTime now = LocalDateTime.now();
//        if (beginTime.isAfter(now)) {
//            return Result.fail("秒杀活动尚未开始");
//        }
//
//        if (endTime.isBefore(now)) {
//            return Result.fail("秒杀活动已经结束");
//        }
//
//        if (stock < 1) {
//            return Result.fail("秒杀券已被抢光");
//        }
//        //一人一单
////        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
    //已经在redis里判断了是否能获取资格，这个判断作为兜底，防止redis失效
        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            Long userId = voucherOrder.getVoucherId();
            RLock lock = redissonClient.getLock("lock:order" + userId);//redission获取可重入锁
            boolean isLock = lock.tryLock();
            //没拿到锁说明有线程在执行
            if (!isLock) {
                log.error("你已经购买过该优惠券");
                return ;
            }
            try {
                //通过代理对象执行事务，才能生效
                 proxy.createVoucherOrder(voucherOrder);
            } finally {
                lock.unlock();

            }
        }
    //将订单对象传入消息队列
    public void sendMessage(VoucherOrder voucherOrder) {
        rabbitTemplate.convertAndSend("boot-queue", voucherOrder);
    };


    /**
     * 将订单信息写入数据库
     * @param voucherOrder
     */
    @Transactional   //为了确保保存和减库存一起所以加事务
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //在订单表中查询该用户是否抢购过该优惠券
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        save(voucherOrder);
//        if (count>0) {
//            log.error("您已经抢购过该优惠券");//lua脚本里已经做过判断，这是作为一个兜底
//                return ;
//            }
            //扣减优惠券的数量
        boolean success = iSeckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0).update();
//        if (!success){
//            log.error("库存不足");
//            return ;
//        }
        //创建订单
        }
    }

